import json
import re


def convert_to_json_format(text):
    """
    将保险条款文本转换为指定JSON格式
    格式: [{"1001":"段落1"}, {"1002":"段落2"}]
    """
    # 清理文本并分割段落
    cleaned_text = re.sub(r'\n\s*\n', '\n', text.strip())
    paragraphs = []
    current_id = 1001

    # 分割主要条款（按章节和条款编号）
    sections = re.split(r'(?=\n第[一二三四五六七八九十]+章)', cleaned_text)
    for section in sections:
        if not section.strip():
            continue

        # 分割具体条款
        clauses = re.split(r'(?=\n第[一二三四五六七八九十]+条)', section)
        for clause in clauses:
            if not clause.strip():
                continue

            # 分割子段落（按数字编号或项目符号）
            sub_paragraphs = re.split(r'(?=\n\s*[0-9．·])', clause)
            for para in sub_paragraphs:
                if not para.strip():
                    continue

                # 清理段落内容
                cleaned_para = ' '.join(para.split())
                paragraphs.append({str(current_id): cleaned_para})
                current_id += 1

    return paragraphs


# 读取原始文本文件
with open('10k_insurance_contract.txt', 'r', encoding='utf-8') as f:
    contract_text = f.read()

# 转换为指定JSON格式
json_data = convert_to_json_format(contract_text)

# 保存到my_text.txt（实际存储为JSON格式）
with open('my_text.txt', 'w', encoding='utf-8') as f:
    json.dump(json_data, f, ensure_ascii=False, indent=2)

print(f"已成功转换并保存到 my_text.txt")
print(f"共生成 {len(json_data)} 个语意段落")
print("文件前3条内容示例：")
print(json.dumps(json_data[:3], ensure_ascii=False, indent=2))